/*
    统计文件中的字符、单词和行数
    字符:
    单词:
    行数:
*/
#include <head.h>

void stat_file(const char *file_name)
{
    int fd = open(file_name,O_RDONLY);
    //FOPEN_ERR(fd);
    char buf[1024];
    int bytes=0;
    int ch_num=0;
    int word_num=0;
    int line_num=0;
    int in_word=0;
    while((bytes = read(fd,buf,sizeof(buf)))>0)
    {
        for(size_t i=0;i<bytes;i++)
        {
            char ch=buf[i];
            ch_num++;

            if(ch == '\n')
            {
                line_num++;
            }

            if(ch==' '||ch=='\n'||ch=='\t')
            {
                if(in_word)
                {
                    word_num++;
                    in_word = 0;
                }
            }
            else
            {
                in_word = 1;
            }
        }
        if (in_word)
        {
            word_num++;
            in_word = 0;
        }
    }
    printf("字符数：%d\n",ch_num);
    printf("单词数：%d\n",word_num);
    printf("行数：%d\n",line_num);
}

int main(int argc,const char *argv[])
{
    stat_file(argv[1]);
    return 0;
}